//
//  SettingViewController.m
//  ebook
//
//  Created by ChenNan on 16/3/22.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "SettingViewController.h"
#import "SetNightModelViewController.h"
#import "ToastView.h"
#import "WebViewController.h"
#import "MISAlertController.h"
#import "FmdbAccess.h"
#import "Book.h"
#import "MBProgressHUD.h"
#import "FontSetViewController.h"

@interface SettingViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UILabel  *textLabel;
@property (nonatomic, retain) UILabel  *textDetailLabel;

@property (nonatomic, copy) NSString *catchesSize;
@property (nonatomic, retain) MBProgressHUD *HUD;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = MTConfigColor(@"MTNavigationBar_background_Color");
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:MTConfigColor(@"MTNavigationBar_title_Color"),                                                                 NSFontAttributeName : [UIFont systemFontOfSize:18]};
    
    self.title = @"设置";
    self.view.backgroundColor = MTConfigColor(@"MTSetting_Bg_Color");
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    _tableView = tableView;
    
    [self createBackBtn];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}

#pragma mark - navi back btn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (0 == section) {
        return 3;
    }
    
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *inditifier = @"settingss";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:inditifier];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:inditifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (0 == indexPath.section) {
        if (0 == indexPath.row) {
            cell.textLabel.text = @"清除缓存";
        }
        if (1 == indexPath.row) {
            cell.textLabel.text = @"定时开启夜间模式";
            NSDictionary *dic = kPeriodTimeOfNight;
            if ([dic[@"isOn"] isEqualToString:@"0"] || !dic) {
                cell.detailTextLabel.text = @"关闭";
            } else {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@-%@", dic[@"fromTime"], dic[@"toTime"]];
            }
            _textDetailLabel = cell.detailTextLabel;
        }
        if (2 == indexPath.row) {
            cell.textLabel.text = @"字体设置";
        }
    } else if (1 == indexPath.section) {
        
        UISwitch *sw = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        sw.frame = CGRectMake(MTScreenW-sw.width-15, 0, 0, 0);
        sw.centerY = cell.centerY;
        [sw addTarget:self action:@selector(switchValueChage:) forControlEvents:UIControlEventTouchUpInside];
        BOOL isContained = NO;
        for (UIView *subView in cell.subviews) {
            if ([subView isKindOfClass:[UISwitch class]]) {
                isContained = YES;
            }
        }
        if (!isContained) {
            [cell addSubview:sw];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        if(indexPath.row == 0){
            cell.textLabel.text = @"阅读屏幕常亮";
            sw.tag = 1;
            sw.on = [[NSUserDefaults standardUserDefaults] boolForKey:kSetLightOfScreen];
        }else if(indexPath.row == 1){
            cell.textLabel.text = @"点击屏幕左侧下翻页";
            sw.tag = 2;
            sw.on = [[NSUserDefaults standardUserDefaults] boolForKey:kSetClipLeftPageDown];
        }
    } else if(indexPath.section == 2){
        if (0 == indexPath.row) {
            cell.textLabel.text = @"服务声明";
        }
        if (1 == indexPath.row) {
            cell.textLabel.text = @"关于";
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (0 == indexPath.section) {
        if (0 == indexPath.row) {
            [self clearCache];
        }
        if (1 == indexPath.row) {
            SetNightModelViewController *nmVC = [[SetNightModelViewController alloc] init];
            [nmVC setSendTimeToSuper:^(NSString *fromTime, NSString *toTime, NSString *isOn){
                NSDictionary *dic = [NSDictionary dictionaryWithObjects:@[fromTime?fromTime:@"", toTime?toTime:@"", isOn?isOn:@""] forKeys:@[@"fromTime", @"toTime", @"isOn"]];
                [[NSUserDefaults standardUserDefaults] setValue:dic forKey:@"nightPeriodOfTime"];
                [_tableView reloadData];
            }];
            NSDictionary *dic = kPeriodTimeOfNight;
            if (dic) {
                nmVC.timeStr = [NSString stringWithFormat:@"%@-%@", dic[@"fromTime"], dic[@"toTime"]];
            } else {
                nmVC.timeStr = nil;
            }
            nmVC.isSwitchOn = [dic[@"isOn"] boolValue];
            [self.navigationController pushViewController:nmVC animated:YES];
        }
        if (2 == indexPath.row) {
            FontSetViewController *fontSetVC = [[FontSetViewController alloc] init];
            [self.navigationController pushViewController:fontSetVC animated:YES];
        }
    } else if (2 == indexPath.section){
        id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        
        WebViewController *webVc = [[WebViewController alloc] init];
        if (0 == indexPath.row) {
            webVc.webViewTitle = @"服务声明";
            webVc.url = dic[@"data"][@"mianze"];
            webVc.showConfirm = YES;
        }
        if (1 == indexPath.row) {
            webVc.webViewTitle = @"关于";
            NSString *url = dic[@"data"][@"about"];
            url = [NSString stringWithFormat:@"%@?version=v%@&package=%@",url,kVersion,kBundleStr];
            webVc.url = url;
        }
        [self.navigationController pushViewController:webVc animated:YES];
    }
}

#pragma mark - 阅读屏幕常亮\左侧下翻页
-(void)switchValueChage:(UISwitch *)sw{
    [[NSUserDefaults standardUserDefaults] setBool:sw.on forKey:sw.tag==1?kSetLightOfScreen:kSetClipLeftPageDown];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:kFreshLocalshelNotification object:nil];//通知书架视图切换
}

#pragma mark - 计算缓存大小
//1:首先计算 单个文件的大小
- (long long)fileSizeAtPath:( NSString *) filePath{
    NSFileManager *manager = [ NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath:filePath error : nil] fileSize];
    }
    return 0 ;
}

//2: 遍历文件夹获得文件夹大小，返回多少 M
- (float)folderSizeAtPath:( NSString *) folderPath{
    NSFileManager *manager = [ NSFileManager defaultManager ];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
    NSString *fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0 * 1024.0);
}

// 显示缓存大小
- (float)filePath
{
    NSString *cachPath = [NSString stringWithFormat:@"%@/Books",PATH_OF_DOCUMENT];
    return [ self folderSizeAtPath :cachPath];
}

#pragma mark - clearCache
// 清理缓存
- (void)clearCache
{
    
    MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@""
                                                                               message:@"清理缓存，将清理掉已下载章节的缓存！是否继续？"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
    MISAlertAction *cancelAction = [MISAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(MISAlertAction *action) {
        MTLog(@"取消");
    }];
    
    MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(MISAlertAction *action) {
        [self showHUD];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [alertController showInViewController:self animated:YES];
}

- (void)showHUD {
    
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _HUD.labelText = @"清除中...";
    }
    [self.view addSubview:_HUD];
    [self.view bringSubviewToFront:_HUD];
    [_HUD show:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self actionWithClearCaches];
    });
}

- (void)hiddenHUD {
    
    if (_HUD) {
        [_HUD removeFromSuperview];
        _HUD = nil;
    }
}

- (void)actionWithClearCaches {
    
    //清理缓存，只清理Books文件夹
    NSString *cachPath = [NSString stringWithFormat:@"%@/Books",PATH_OF_DOCUMENT];
    NSArray *files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
    for ( NSString *p in files) {
        NSError *error = nil ;
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    
    [[NSURLCache sharedURLCache ] removeAllCachedResponses];
    [self clearWkWebviewCache];
    [self clearCachSuccess];
}

/** 清理缓存的方法，这个方法会清除缓存类型为HTML类型的文件*/
- (void)clearWkWebviewCache {
    
    if([[UIDevice currentDevice].systemVersion floatValue] >=9.0) {
        
        NSSet*websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        
        NSDate*dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
        
    }else{
        
        NSString*libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES)objectAtIndex:0];
        
        NSString*cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError*errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}

- ( void )clearCachSuccess
{
    [self hiddenHUD];
    [ToastView showMsg:@"缓存清理成功" inView:self.view isCenter:YES];
    _textLabel.text = @"0.00M";
}

@end
